<?php

 	include_once("./helper.php");
	
	include_once("./db.php");

	if($_REQUEST["guest"])
	{
		$_REQUEST["txtUser"] = "Guest " . rand(1, 1000000);
		
		$_REQUEST["txtPass"] = "Guest " . rand(1, 1000000);
		
		$_REQUEST["hdnSignup"] = 1;
		
		$_REQUEST["loginKeepLogedin"] = 1;
	}
	else
	{
	
		if((!$_REQUEST["txtUser"] || !$_REQUEST["txtPass"]) || ($_REQUEST["hdnSignup"] && !$_REQUEST["txtPass2"]))
			return json_result_encode("Please fill both fields.");

		if($_REQUEST["hdnSignup"] && strlen($_REQUEST["txtPass"]) < 6)
			return json_result_encode("Minimum password length is 6 characters.");
			
		if($_REQUEST["hdnSignup"] && $_REQUEST["txtPass2"] != $_REQUEST["txtPass"])
			return json_result_encode("Passwords doesn't match.");
	}
	
	$fields = array(
		"UserName"	=> $_REQUEST["txtUser"],
		"UserEmail"	=> $_REQUEST["txtUser"],
		"UserPassword" => md5($_REQUEST["txtPass"]),
	); 

	if($_REQUEST["hdnSignup"])
	{
		$userId = db_insert("User", $fields);
	
		if(!$userId['Id'])
			return json_result_encode("Wait a minute! We know this email address. Y u no try <a href='#'>recovering you password</a>?");
		
		$tagId = db_scalar("SELECT Id FROM Tag WHERE Name = 'Basic'");
		
		$fieldsTag = array(
			"TagUserTagId"	=> $tagId,
			"TagUserUserId" => $userId['Id']); 
		
		db_insert('TagUser', $fieldsTag);
		
	}
	
	$sql = "SELECT u.Id, u.Name, u.Email, u.Password from User u WHERE u.Email = @UserEmail AND (u.Password = @UserPassword  OR md5(u.Password) = @UserPassword) ";
	
	$db_res = db_select($sql, $fields);
	
	if(mysql_num_rows($db_res) != 1)
	{
		setcookie("user", null, time(), "/");
		
		setcookie("user", null, time(), "/");
	
		json_result_encode("Email or password not found. <a href='#'>Recover Password</a>.");
	}
	
	$res["user"] = mysql_fetch_array($db_res, MYSQL_ASSOC);	
	
	$sql = "SELECT t.Id, t.Name FROM Tag t, TagUser tu WHERE t.Id = tu.TagId AND tu.UserId = @TagUserUserId";
	
	$db_res = db_select($sql, array( 'TagUserUserId' => $userId ));

	while($r = mysql_fetch_array($db_res, MYSQL_ASSOC))
		$tags[] = $r;	
	
	$_SESSION["user"]["tags"] = $tags;	
	
	$_SESSION = $res;
	
	//if($_REQUEST["loginKeepLogedin"])
	{
		setcookie("Id", $res["user"]["Id"], time()+60*60*24*30, "/");
		setcookie("Email", $res["user"]["Email"], time()+60*60*24*30, "/");
		setcookie("Name", $res["user"]["Name"], time()+60*60*24*30, "/");
		setcookie("Password", $res["user"]["Password"], time()+60*60*24*30, "/");
	}
	
	json_result_encode($res);
?>